import React, { useState, useEffect, useCallback } from "react";
import { Modal, Alert, Form, Radio, Button, Upload, Card, Switch, Tooltip, message } from "antd";
import { SettingTwoTone, FolderOpenTwoTone } from "@ant-design/icons";

import { CommonModal } from "@/views/components/CommonModal";
import Iconfont from "@/components/IconFont";
import { useExportTask } from "@/views/hooks/useExportTask";
import { useImportTask } from "@/views/hooks/useImportTask";

import { getImportTemplateUrl } from "../../../service";
import ProgressModal from "@/views/components/UIModal/ProgressModal";
import ImportResultModal from "@/views/components/UIModal/ImportResultModal";

import { isEmpty } from "lodash";
import useUserStore from '@/stores/user.js'

const { Dragger } = Upload;

const ExcelImportModal = ({ onCancel }) => {
	const [visible, setVisible] = useState("ImportFileModal");
	// const createTaskData = {
	// 	taskType: 1205
	// };
	const { percent, step, result, handleDownload, startTask, clearTimer } = useImportTask();

	const userInfo = useUserStore(state => state.userInfo);

	useEffect(() => {
		if (step.first === true) {
			setVisible("ProgressModal");
		}
		if (step.second === true) {
			setVisible("ImportResultModal");
		}
		if (step.first === false || step.second === false || step.third === true) {
			onCancel();
		}
	}, [step]);

	//////////////////////////
	const ImportFileModal = React.memo(props => {
		const [radioValue, setRadioValue] = useState(1);

		if (props.visible !== "ImportFileModal") return <></>;

		const onRadioChange = e => {
			setRadioValue(e.target.value);
		};

		const [file, setFile] = useState();
		const DraggerProps = {
			name: "file",
			maxCount: 1,
			multiple: false,
			action: "",
			onChange(info) {
				// const { status } = info.file;
				// if (status !== "uploading") {
				// 	console.log(info.file, info.fileList);
				// }
				// if (status === "done") {
				// 	message.success(`${info.file.name} file uploaded successfully.`);
				// } else if (status === "error") {
				// 	message.error(`${info.file.name} file upload failed.`);
				// }
			},
			onDrop(e) {
				// console.log("Dropped files", e.dataTransfer.files);
			},
			beforeUpload(f) {
				console.log("beforeUpload", f);
				setFile(f);
				return false;
			}
		};

		const { downloadExportTask } = useExportTask();

		const handleOk = useCallback(() => {
			if (!file) {
				message.warning("请上传表格");
				return;
			}
			const businessParam = JSON.stringify({
				uuid: userInfo.uuid,
				applyUser: userInfo.id,
				applyName: userInfo.account
			});

			const formData = new FormData();

			formData.append("file", file);
			formData.append("taskType", 1205);
			formData.append("businessParam", businessParam);

			props.startTask(formData);
		}, [file, radioValue]);
		const tryExportExample = () => {
			getImportTemplateUrl({ taskType: 1205 }).then(res => {
				const { data, msg: msg1, message: msg2 } = res;
				if (data && typeof data === "string" && String(data).startsWith("http")) {
					window.open(data);
				} else {
					message.error(msg1 || msg2 || "下载文件失败");
				}
			});
		};

		return (
			<CommonModal
				title={{ title: "Excel导入数据" }}
				open={true}
				width={528}
				okText="保存"
				onCancel={onCancel}
				onOk={handleOk}
			>
				<Alert
					message={
						<div>
							<div style={{ fontSize: 12, color: "#4E5969" }}>1、请先导出列表数据，然后编辑需要更新的数据再导入。</div>
							<div style={{ fontSize: 12, color: "#4E5969" }}>2、门店ID：必填。该数据可以通过导出表格得到；系统将根据门店ID、以及对应字段进行导入</div>
							<div style={{ fontSize: 12, color: "#4E5969" }}>3、导入支持：区域编码、门店备注、门店顺序、采购付款节点、自定义地址、拿货员、退货员。</div>
						</div>
					}
					action={
						<Button type="primary" ghost style={{ marginLeft: 10 }} onClick={tryExportExample}>
							下载模板
						</Button>
					}
					type="info"
					showIcon
				/>
				<div style={{ marginTop: 10, fontSize: 14, color: "", fontWeight: 'bolder' }}>
					<div>导入表格</div>
				</div>
				<Dragger {...DraggerProps} style={{ marginTop: 10, marginBottom: 24, backgroundColor: "#F4F7FF" }}>
					<p className="ant-upload-drag-icon">
						<Iconfont type="iconExcel" style={{ fontSize: 40 }} />
					</p>
					<p>点击或将文件拖拽到这里上传,只支持Excel文件</p>
					<p className="light-gray">最大50mb，单次最多5000条商品</p>
				</Dragger>
			</CommonModal>
		);
	});

	return (
		<>
			<ImportFileModal visible={visible} startTask={startTask} />
			<ProgressModal
				visible={visible === "ProgressModal"}
				type="progress"
				percent={percent}
				title="导入更新商品"
				msg="正在导入商品，请等待..."
				skip
				onCancel={() => {
					{
						onCancel();
						clearTimer();
					}
				}}
			/>
			<ImportResultModal
				visible={visible === "ImportResultModal"}
				result={result}
				handleExportFailed={handleDownload}
				handleCancel={onCancel}
			/>
		</>
	);
};
export default ExcelImportModal;
